<template>
  <el-card class="ai-chat-container" ref="chatMessagesRef">
    <div class="message-list">
      <el-scrollbar height="calc(100vh - 400px)">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          class="message" 
          :class="{ 
            'user-message': message.isUser, 
            'ai-message': !message.isUser 
          }"
        >
          <div class="message-avatar">
            <el-avatar :src="message.isUser ? user : auto"/>
          </div>
          <div class="message-content">
            <div class="message-meta">
              <span class="message-time">{{ new Date().toLocaleTimeString() }}</span>
            </div>
            <div class="message-bubble" :class="{ 'typing': message.isTyping }">
              <div v-html="md.render(message.text)"></div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </el-card>
  <el-card class="input-card">
      <div class="quick-actions">
        <el-button 
          type="primary" 
          plain
          @click="() => inputMessage = '查询会议室'"
          class="quick-action-button"
        >
          查询会议室
        </el-button>
        <el-button 
          type="primary" 
          plain
          @click="() => inputMessage = '查询我的预约'"
          class="quick-action-button"
        >
          查询我的预约
        </el-button>
        <el-button 
          type="primary" 
          plain
          @click="() => inputMessage = '我要取消预约'"
          class="quick-action-button"
        >
          我要取消预约
        </el-button>
      </div>
      <div class="input-area">
        <el-input 
          v-model="inputMessage" 
          @keyup.enter="sendMessage" 
          placeholder="输入消息..." 
          clearable
          class="input-box"
        />
        <el-button 
          type="primary" 
          @click="sendMessage"
          :loading="isLoading"
          class="send-button"
        >
          发送
        </el-button>
      </div>
  </el-card>
</template>

<script setup>
import { ref, nextTick, watch } from 'vue';
import service from '../utils/request';
import { useUserStore } from '../stores/UserStore';
import MarkdownIt from 'markdown-it';
import auto from '../assets/DouShaBao.png'
import user from '../assets/user.png'

const md = new MarkdownIt();

const userStore = useUserStore()
const isLoading = ref(false);
const chatMessagesRef = ref(null);
const messages = ref([
  { text: '你好！我是会议室的AI助手，有什么可以帮您的吗？', isUser: false }
]);
const inputMessage = ref('');

// 添加自动滚动到底部的函数
const scrollToBottom = async () => {
  await nextTick();
  if (chatMessagesRef.value) {
    const scrollbar = chatMessagesRef.value.$el.querySelector('.el-scrollbar__wrap');
    if (scrollbar) {
      scrollbar.scrollTo({
        top: scrollbar.scrollHeight,
        behavior: 'smooth'
      });
    }
  }
};

// 监听消息变化，自动滚动到底部
watch(() => messages.value.length, () => {
  scrollToBottom();
});

// 监听消息内容变化，自动滚动到底部
watch(() => messages.value[messages.value.length - 1]?.text, () => {
  scrollToBottom();
});

const escapeHtml = (text) => {
  const map = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;',
  };
  return text.replace(/[&<>"']/g, (m) => map[m]);
};

const sendMessage = async () => {
  if (!inputMessage.value.trim()) return;

  const escapedText = escapeHtml(inputMessage.value);
  messages.value.push({ text: escapedText, isUser: true });
  inputMessage.value = '';
  isLoading.value = true;
  
  const headers = new Headers();
  headers.append('Content-Type', 'application/json');

  try {
    // 添加临时响应消息
    const botMessage = { text: '', isUser: false };
    messages.value.push(botMessage);

    const response = await fetch(`${service.defaults.baseURL}ai/stream?message=${escapedText}`, {
        method: 'GET',
        headers: {
          ...headers,
          'Token': userStore.token
        }
      })

    // 检查响应是否成功
    if (response.status === 200) {
      const reader = response.body.getReader();
      const stream = new ReadableStream({
        start(controller) {
          function push() {
            reader.read().then(({ done, value }) => {
              if (done) {
                controller.close();
                return;
              }
              controller.enqueue(value);
              push();
            }).catch(err => {
              console.error('Stream reading error:', err);
              controller.error(err);
            });
          }
          push();
        }
      });

      const textDecoder = new TextDecoder('utf-8');
      const readerStream = stream.getReader();
      
      while (true) {
        const { done, value } = await readerStream.read();
        if (done) break;
        const textChunk = textDecoder.decode(value, { stream: true });
        // 更新最后一条消息内容
        botMessage.text += textChunk;
        // 创建新数组触发响应式更新
        messages.value = [...messages.value];
        // 每次更新后滚动到底部
        await scrollToBottom();
      }

    } else {
      ElMessage.error('请求失败，状态码：' + response.status);
    }
  } catch (error) {
    console.error('Error:', error);
    messages.value.push({ 
      text: '⚠️ 抱歉，出现错误，请稍后重试。', 
      isUser: false 
    });
  } finally {
    isLoading.value = false;
    await scrollToBottom();
  }
}

</script>

<style scoped>
.ai-chat-container {
  position: fixed;
  top: 80px;
  left: calc(50% + 120px);
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  height: calc(100vh - 240px);
  width: 800px;
  padding: 1.5rem;
  border-radius: 20px;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  overflow: hidden;
  z-index: 99;
}

.message-list {
  flex: 1;
  margin-bottom: 1rem;
  padding: 0 1rem;
  height: 100%;
}

.message-list :deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

.message-list :deep(.el-scrollbar__bar.is-horizontal) {
  display: none;
}

.message-list :deep(.el-scrollbar__bar.is-vertical) {
  width: 6px;
  right: 0;
}

.message-list :deep(.el-scrollbar__thumb) {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.message {
  display: flex;
  margin-bottom: 2rem;
  max-width: 85%;
  transition: all 0.3s ease;
  animation: messageAppear 0.3s ease-out;
  word-break: break-word;
}

@keyframes messageAppear {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-avatar {
  margin-right: 1rem;
  align-self: flex-end;
  transition: all 0.3s ease;
}

.message-avatar:hover {
  transform: scale(1.1);
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.message-meta {
  font-size: 0.75rem;
  color: var(--el-text-color-secondary);
  margin-bottom: 0.25rem;
  opacity: 0.8;
}

.message-bubble {
  padding: 1rem 1.25rem;
  border-radius: 1.25rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  position: relative;
  transition: all 0.3s ease;
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.message-bubble.typing::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 20px;
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid var(--el-bg-color-page);
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.user-message .message-avatar {
  margin-right: 0;
  margin-left: 1rem;
}

.user-message .message-bubble {
  background: linear-gradient(135deg, #3949ab 0%, #5c6bc0 100%);
  color: white;
  border-radius: 1.25rem 1.25rem 0 1.25rem;
}

.user-message .message-bubble.typing::after {
  right: 20px;
  left: auto;
  border-top-color: #5c6bc0;
}

.ai-message {
  margin-right: auto;
}

.ai-message .message-bubble {
  background: white;
  color: var(--el-text-color-regular);
  border-radius: 1.25rem 1.25rem 1.25rem 0;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.input-card {
  position: fixed;
  bottom: 20px;
  left: calc(50% + 120px); /* 调整左侧位置，考虑导航栏宽度 */
  transform: translateX(-50%);
  width: 800px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  background: white;
  border: 1px solid rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  padding: 1.5rem;
  z-index: 100;
}

.quick-actions {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

.quick-action-button {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid rgba(0, 0, 0, 0.05);
  color: #3949ab;
  font-weight: 500;
  transition: all 0.3s ease;
  padding: 8px 16px;
  border-radius: 12px;
}

.quick-action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(57, 73, 171, 0.1);
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
}

.input-area {
  display: flex;
  gap: 1rem;
  align-items: center;
  padding: 0.5rem;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 16px;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.input-box {
  flex: 1;
  border-radius: 12px;
}

.input-box :deep(.el-input__wrapper) {
  background: transparent;
  box-shadow: none;
  padding: 0.75rem 1rem;
}

.input-box :deep(.el-input__inner) {
  font-size: 1rem;
  color: #3949ab;
}

.send-button {
  border-radius: 12px;
  padding: 0.75rem 1.5rem;
  font-weight: 500;
  background: linear-gradient(135deg, #3949ab 0%, #5c6bc0 100%);
  border: none;
  transition: all 0.3s ease;
}

.send-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(57, 73, 171, 0.2);
}

@media (max-width: 850px) {
  .ai-chat-container,
  .input-card {
    width: 95%;
    margin-left: auto;
    margin-right: auto;
  }
  
  .input-card {
    left: 50%;
  }
  
  .message {
    max-width: 90%;
  }
  
  .quick-actions {
    justify-content: center;
  }
  
  .input-area {
    flex-direction: column;
  }
  
  .send-button {
    width: 100%;
  }
}
</style>